const { equipmentData, equipmentMap, getEquipmentByName, uniqueEquipmentTypes } = require('../../data/equipment.js');
const { equipmentSets, getSetAttributeName, getSetAttributeUnit } = require('../../data/sets.js');
const { workers, physicalWorkers, magicWorkers, jobData } = require('../../data/job.js');
const { allElements } = require('../../data/attribute.js');
const { enchantData } = require('../../data/enchant.js');

Page({
    onShareAppMessage() {
        return {
            title: '南柯工具助手-DNF手游伤害计算器', // 转发标题（必填）
            path: '/pages/calculator/index', // 转发路径（默认当前页面）
            imageUrl: '/image/toolicons/dnfdamage.png' // 自定义图片（可选，比例 5:4）
        };
    },
    onShareTimeline() {
        return {
            title: '南柯工具助手-DNF手游伤害计算器', // 转发标题（必填）
            path: '/pages/calculator/index', // 转发路径（默认当前页面）
            imageUrl: '/image/toolicons/dnfdamage.png' // 自定义图片（可选，比例 5:4）
        };
    },
    data: {
        // 标签集合 {'武器':['', '', ''],...}
        thisEquipmentLabelMap: {},
        // 装备类型集合 ['武器', '头肩', '鞋',...]
        thisEquipmentTypes: uniqueEquipmentTypes,
        // 选择的装备展示的标签 ex: {武器: "破碎之命运(短剑)(60级)", …}
        selectedEquipmentLabelMap: {},
        // 选择的装备 ex:{'武器':{'装备部位':'',...},...}
        selectedEquipmentMap: {},
        // 选择的职业 ex: 剑魂
        selectedJob: '',
        // 职业列表
        jobs: workers,
        // 属性列表
        attributes: allElements,
        // 选择的属性
        selectedAttribute: '',
        armorTypes: ['上衣', '下装', '头肩', '腰带', '鞋'],
        armorCategorys: ['轻甲', '布甲', '皮甲', '重甲', '板甲'],
        // 新增：防具多列选择器数据
        equipmentMultiArray: {},
        equipmentMultiIndex: {},
        // 计算结果
        damageResult: '0',
        // 套装效果
        setEffects: '',
        // 是否需要重新计算
        needRecalculate: false,
        // 属性汇总
        nowTotalAttributes: null,
        // 历史记录
        damageHistory: [],
        // 徽章选项 10-1
        badgeOptions: Array.from({ length: 10 }, (_, i) => 10 - i),
        // 装备徽章数据
        equipmentBadges: {},
        // 徽章颜色配置
        badgeColors: {
            red: ['上衣', '武器', '下装'],
            green: ['项链', '戒指'],
            silver: ['团队勋章', '冒险勋章', '工会勋章'],
            platinum: ['称号', '辅助装备']
        },
        // 强化相关
        reinforceOptions: Array.from({ length: 21 }, (_, i) => 20 - i), // 20到0
        equipmentReinforce: {}, // 存储装备强化数值
        canReinforceTypes: ['武器', '上衣', '头肩', '下装', '辅助装备', '项链', '戒指', '鞋', '腰带', '手镯'], // 可以强化的部位
        // 装备附魔数据
        enchantOptions: enchantData,
        equipmentEnchant: {}, // 存储每个部位选择的附魔
        // 可附魔的部位
        enchantableTypes: ["武器", '上衣', '下装', '鞋', '腰带', '头肩', '冒险勋章', '团队勋章', '辅助装备', '手镯', '项链', '戒指']
    },
    onLoad() {
        const loadRes = this.loadOpt();
        this.initEquipmentMultiArray();
        if (!loadRes) {
            Object.entries(equipmentMap).forEach(([type, items]) => {
                const itemName = items.map(item =>
                    item.装备名称 + '(' + item.装备类型 + ')' + '(' + item.装备等级 + '级)'
                );
                this.setData({
                    [`thisEquipmentLabelMap.${type}`]: itemName,
                    // 根据部位设置徽章
                    [`equipmentBadges.${type}`]: this.getBadgeInitialValue(type, itemName),
                    [`equipmentReinforce.${type}`]: this.data.canReinforceTypes.includes(type) ? 20 : null,
                    [`equipmentEnchant.${type}`]: this.data.enchantableTypes.includes(type) ? this.data.enchantOptions[type][this.data.enchantOptions[type].length - 1] : null
                });
            });
            this.setData({
                selectedJob: workers[3],
                selectedAttribute: allElements[1]
            });
            this.autoSelectEquipment();
        } else {
            Object.entries(equipmentMap).forEach(([type, items]) => {
                const itemName = items.map(item =>
                    item.装备名称 + '(' + item.装备类型 + ')' + '(' + item.装备等级 + '级)'
                );
                this.setData({
                    [`thisEquipmentLabelMap.${type}`]: itemName,
                    needRecalculate: true
                });
            });

        }
        this.getSetEffects();
    },
    saveOpt() {
        wx.setStorage({
            'key': 'userOpt',
            data: {
                'selectedEquipmentLabelMap': this.data.selectedEquipmentLabelMap,
                'selectedEquipmentMap': this.data.selectedEquipmentMap,
                'selectedJob': this.data.selectedJob,
                'selectedAttribute': this.data.selectedAttribute,
                'equipmentBadges': this.data.equipmentBadges,
                'equipmentReinforce': this.data.equipmentReinforce,
                'equipmentEnchant': this.data.equipmentEnchant
            }
        })
    },
    loadOpt() {
        try {
            const settings = wx.getStorageSync('userOpt')
            if (settings == '') return false;
            console.log('load opt', settings)
            this.setData({
                selectedEquipmentLabelMap: settings.selectedEquipmentLabelMap || {},
                selectedEquipmentMap: settings.selectedEquipmentMap || {},
                selectedJob: settings.selectedJob || '',
                selectedAttribute: settings.selectedAttribute || '',
                equipmentBadges: settings.equipmentBadges || {},
                equipmentReinforce: settings.equipmentReinforce || {},
                equipmentEnchant: settings.equipmentEnchant || {}
            })
            return true;
        } catch (e) {
            console.error('加载设置失败', e)
            return false;
        }
    },
    // 初始化装备多列选择器数据
    initEquipmentMultiArray() {
        let multiArray = {};
        let multiIndex = {};
        const parts = ['上衣', '下装', '头肩', '腰带', '鞋', '武器'];
        parts.forEach(part => {
            // 第二列初始化为第一个装备类型的装备
            const partEquipments = equipmentData
                .filter(item => item.装备部位 === part);
            // 获取该部位所有可用的装备类型
            const availableTypes = [...new Set(partEquipments.map(item => item.装备类型))];
            // 获取第一个装备类型的装备列表
            const firstTypeEquipments = partEquipments
                .filter(item => item.装备类型 === availableTypes[0])
                .map(item => `${item.装备名称}(${item.装备等级}级)`);

            // 设置多列选择器的数据
            multiArray[part] = [availableTypes, firstTypeEquipments];
            multiIndex[part] = [0, 0];
        });
        // console.log(multiArray);
        this.setData({
            equipmentMultiArray: multiArray,
            equipmentMultiIndex: multiIndex
        });
    },

    // 处理多列选择器列变化
    onEquipmentColumnChange(e) {
        const { type } = e.currentTarget.dataset;
        const { column, value } = e.detail;

        if (column === 0) {
            // 获取选中的装备类型
            const selectedType = this.data.equipmentMultiArray[type][0][value];

            // 更新第二列的装备列表
            const equipmentList = equipmentData
                .filter(item =>
                    item.装备部位 === type &&
                    item.装备类型 === selectedType
                )
                .map(item => `${item.装备名称}(${item.装备等级}级)`);

            // 更新数据
            this.setData({
                [`equipmentMultiArray.${type}[1]`]: equipmentList,
                [`equipmentMultiIndex.${type}[0]`]: value,
                [`equipmentMultiIndex.${type}[1]`]: 0
            });
        }
    },

    // 处理多列选择器选择
    onEquipmentMultiChange(e) {
        const { type } = e.currentTarget.dataset;
        const { value } = e.detail;

        // 获取选中的装备类型和装备名称
        const selectedType = this.data.equipmentMultiArray[type][0][value[0]];
        const selectedEquipmentName = this.data.equipmentMultiArray[type][1][value[1]].split('(')[0];

        // 获取完整的装备数据
        const equipment = equipmentData.find(item =>
            item.装备部位 === type &&
            item.装备类型 === selectedType &&
            item.装备名称 === selectedEquipmentName
        );

        if (equipment) {
            this.setData({
                [`selectedEquipmentMap.${type}`]: equipment,
                [`selectedEquipmentLabelMap.${type}`]: `${equipment.装备名称}(${equipment.装备类型})(${equipment.装备等级}级)`,
                [`equipmentMultiIndex.${type}`]: value,
                needRecalculate: true
            });
        }
    },
    // 获取徽章初始值
    getBadgeInitialValue(type, labelValue) {
        // 称号、勋章类和骨戒只有一个徽章槽位
        if (this.data.badgeColors.silver.includes(type) ||
            this.data.badgeColors.platinum.includes(type) ||
            (type === '戒指' && labelValue !== undefined && labelValue.includes("骨戒"))) {
            return { 1: 9 };
        }
        // 其他部位有两个徽章槽位
        if (this.data.badgeColors.red.includes(type) ||
            this.data.badgeColors.green.includes(type) ||
            this.data.badgeColors.silver.includes(type) ||
            this.data.badgeColors.platinum.includes(type)) {
            return { 1: 9, 2: 9 };
        }
        return null; // 其他部位不显示徽章
    },
    // 处理徽章选择
    onBadgeChange(e) {
        const { type, slot } = e.currentTarget.dataset;
        const value = this.data.badgeOptions[e.detail.value];
        this.setData({
            [`equipmentBadges.${type}.${slot}`]: value,
            needRecalculate: true
        });
    },
    // 处理强化选择
    onReinforceChange(e) {
        const { type } = e.currentTarget.dataset;
        const value = this.data.reinforceOptions[e.detail.value];
        this.setData({
            [`equipmentReinforce.${type}`]: value,
            needRecalculate: true
        });
    },
    // 附魔选择器
    onEnchantChange(e) {
        const { type } = e.currentTarget.dataset;
        const value = e.detail.value;
        const enchant = this.data.enchantOptions[type][value];
        this.setData({
            [`equipmentEnchant.${type}`]: enchant,
            needRecalculate: true
        });
    },
    // 检查并获取套装效果
    getSetEffects() {
        const equipped = Object.values(this.data.selectedEquipmentMap);
        let setEffects = {};
        let setEffectsText = '';
        let activatedSets = []; // 记录已激活的套装
        // 遍历所有套装
        Object.entries(equipmentSets).forEach(([setName, setData]) => {
            const equippedPieces = setData.pieces.filter(piece =>
                equipped.some(equipment => equipment.装备名称 === piece)
            );
            const pieceCount = equippedPieces.length;
            // 只处理已经触发效果的套装（至少2件)}
            if (pieceCount >= 2) {
                // 记录激活的套装
                activatedSets.push({
                    name: setName,
                    count: pieceCount,
                    effects: {}
                });
                // 应用套装效果
                Object.entries(setData.effects).forEach(([reqCount, effects]) => {
                    if (pieceCount >= parseInt(reqCount)) {
                        Object.entries(effects).forEach(([attr, value]) => {
                            if (attr === 'element_direction') {
                                setEffects[attr] = value;
                                activatedSets[activatedSets.length - 1].effects[attr] = value;
                                return;
                            }
                            setEffects[attr] = value + (setEffects[attr] || 0);
                            activatedSets[activatedSets.length - 1].effects[attr] =
                                (activatedSets[activatedSets.length - 1].effects[attr] || 0) + value;
                        });
                    }
                });
            }
        });

        // 如果有激活的套装，显示套装效果
        if (activatedSets.length > 0) {
            activatedSets.forEach(set => {
                setEffectsText += `${set.name} (${set.count}件):\n`;
                Object.entries(set.effects).forEach(([attr, value]) => {
                    let attrName = getSetAttributeName(attr);
                    setEffectsText += `  ${attrName} +${value}${getSetAttributeUnit(attr)}\n`;
                });
                setEffectsText += '\n';
            });
        }
        this.setData({
            setEffects: setEffectsText || ''
        });
        return setEffects;
    },

    // 计算装备属性总和
    calculateTotalAttributes() {
        let total = {
            '属强加成方向': this.data.selectedAttribute
        };
        const jobInfo = jobData[this.data.selectedJob];
        // 累加装备基础属性
        Object.entries(this.data.selectedEquipmentLabelMap).forEach(([key, itemName]) => {
            if (itemName !== undefined) {
                const name = itemName.split('(')[0];
                const equipment = getEquipmentByName(key, name);
                if (equipment) {
                    // 累加装备属性
                    Object.keys(equipment).forEach((key) => {
                        if ((key === '属强加成' || key === '属性伤害百分比')) {
                            const directions = equipment.属强加成方向 ? equipment.属强加成方向.split(',') : [];
                            // 如果是全属性或者包含选择的属性，才累加属性值
                            if (equipment.属强加成方向 === "全属性" || directions.includes(this.data.selectedAttribute)) {
                                total[key] = (total[key] || 0) + equipment[key];
                            }
                            return;
                        }

                        // 如果属性是数值类型，且不是装备等级则累加
                        if (typeof equipment[key] == 'number' && key !== '装备等级' && key != '属强加成方向') {
                            total[key] = (total[key] || 0) + equipment[key];
                        }
                    });
                    // 魔法封印加成和防具精通
                    if (['布甲', '皮甲', '轻甲', '重甲', '板甲'].includes(equipment['装备类型'])) {
                        total['智力'] = (total['智力'] || 0) + 34 + 18;
                        total['力量'] = (total['力量'] || 0) + 34 + 18;
                        if (jobInfo && jobInfo.armorMaster === equipment['装备类型']) {
                            const armorBonus = jobInfo.masterBonus.armor[key];
                            if (armorBonus) {
                                Object.entries(armorBonus).forEach(([attr, value]) => {
                                    total[attr] = (total[attr] || 0) + value;
                                });
                            }
                        }
                    }
                    if ('武器' === equipment['装备类型']) {
                        total['黄字'] = (total['黄字'] || 0) + 6;
                        total['智力'] = (total['智力'] || 0) + 18 + 18;
                        total['力量'] = (total['力量'] || 0) + 18 + 18;
                        if (jobInfo && jobInfo.weaponMaster.includes(equipment['装备类型'])) {
                            const weaponBonus = jobInfo.masterBonus.weapon[key];
                            if (weaponBonus) {
                                Object.entries(weaponBonus).forEach(([attr, value]) => {
                                    total[attr] = (total[attr] || 0) + value;
                                });
                            }
                        }
                    }
                    if (['戒指', '项链', '戒指'].includes(equipment['装备类型'])) {
                        total['属强加成'] = (total['属强加成'] || 0) + 14;
                        if (equipment['装备等级'] <= 40) {
                            total['属强加成'] = total['属强加成'] - 8;
                        }
                    }
                }
            }
        });
        // console.log(total)

        // 添加套装效果
        const setEffects = this.getSetEffects();
        // console.log(setEffects)
        Object.entries(setEffects).forEach(([attr, value]) => {
            const key = getSetAttributeName(attr);
            if (total.hasOwnProperty(key) && typeof value === 'number') {
                if ((key === '属强加成' || key === '属性伤害百分比') &&
                    (setEffects.element_direction !== this.data.selectedAttribute && setEffects.element_direction !== "全属性")) {
                    return;
                }
                if (typeof total[key] !== 'number') {
                    return;
                }
                total[key] += value;
            }
        });
        console.log(total)
        return total;
    },
    // 计算伤害
    calculateDamage() {
        if (!this.data.needRecalculate) return;

        const totalAttributes = this.calculateTotalAttributes();
        const isPhysicalJob = physicalWorkers.includes(this.data.selectedJob);

        // 计算徽章加成
        Object.entries(this.data.equipmentBadges).forEach(([type, badges]) => {
            if (!badges) return;

            // 红色徽章加成力智
            if (this.data.badgeColors.red.includes(type)) {
                const redBadgeValues = [8, 13, 18, 24, 29, 34, 39, 45, 50, 55];
                Object.values(badges).forEach(level => {
                    if (level > 0) {
                        totalAttributes['力量'] = (totalAttributes['力量'] || 0) + redBadgeValues[level - 1];
                        totalAttributes['智力'] = (totalAttributes['智力'] || 0) + redBadgeValues[level - 1];
                    }
                });
            }

            // 绿色徽章加成物爆魔爆
            if (this.data.badgeColors.green.includes(type)) {
                const greenBadgeValues = [8, 12, 16, 22, 26, 30, 35, 39, 43, 46];
                Object.values(badges).forEach(level => {
                    if (level > 0) {
                        totalAttributes['物爆'] = (totalAttributes['物爆'] || 0) + greenBadgeValues[level - 1];
                        totalAttributes['魔爆'] = (totalAttributes['魔爆'] || 0) + greenBadgeValues[level - 1];
                    }
                });
            }

            // 银色徽章加成力智
            if (this.data.badgeColors.silver.includes(type)) {
                const silverBadgeValues = [16, 23, 29, 36, 42, 49, 55, 62, 69, 75];
                Object.values(badges).forEach(level => {
                    if (level > 0) {
                        totalAttributes['力量'] = (totalAttributes['力量'] || 0) + silverBadgeValues[level - 1];
                        totalAttributes['智力'] = (totalAttributes['智力'] || 0) + silverBadgeValues[level - 1];
                    }
                });
            }

            // 白金徽章加成属强
            if (this.data.badgeColors.platinum.includes(type)) {
                const platinumBadgeValues = [2, 5, 8, 11, 14, 17, 20, 23, 26, 29];
                Object.values(badges).forEach(level => {
                    if (level > 0) {
                        totalAttributes['属强加成'] = (totalAttributes['属强加成'] || 0) + platinumBadgeValues[level - 1];
                    }
                });
            }
        });

        // 计算强化加成
        Object.entries(this.data.equipmentReinforce).forEach(([type, level]) => {
            if (!level || level === 0) return;

            // 武器强化加成
            if (type === '武器') {
                const weaponReinforceValues = [1, 4, 11, 20, 33, 49, 67, 89, 114, 141, 172, 206, 242, 282, 325, 370, 419, 471, 525, 583];
                if (level > 0 && level <= 20) {
                    totalAttributes['物理攻击力'] = (totalAttributes['物理攻击力'] || 0) + weaponReinforceValues[level - 1];
                    totalAttributes['魔法攻击力'] = (totalAttributes['魔法攻击力'] || 0) + weaponReinforceValues[level - 1];
                }
            }
            // 防具强化加成（上衣、头肩、下装、鞋、腰带）
            else if (this.data.armorTypes.includes(type)) {
                const armorReinforceValues = [1, 2, 3, 4, 5, 7, 9, 11, 13, 15, 17, 19, 21, 26, 30, 34, 38, 42, 46, 48];
                if (level > 0 && level <= 20) {
                    totalAttributes['力量'] = (totalAttributes['力量'] || 0) + armorReinforceValues[level - 1];
                    totalAttributes['智力'] = (totalAttributes['智力'] || 0) + armorReinforceValues[level - 1];
                }
            }
            // 首饰强化加成（项链、戒指、手镯）
            else if (['项链', '戒指', '手镯'].includes(type)) {
                const accessoryReinforceValues = [4, 5, 6, 8, 10, 12, 14, 16, 19, 22, 25, 29, 32, 36, 40, 44, 49, 54, 59, 64];
                if (level > 0 && level <= 20) {
                    totalAttributes['力量'] = (totalAttributes['力量'] || 0) + accessoryReinforceValues[level - 1];
                    totalAttributes['智力'] = (totalAttributes['智力'] || 0) + accessoryReinforceValues[level - 1];
                }
            }
            // 辅助装备强化加成
            else if (type === '辅助装备') {
                const supportReinforceValues = [4, 5, 6, 8, 10, 12, 14, 16, 19, 22, 25, 29, 32, 36, 40, 44, 49, 54, 59, 64];
                if (level > 0 && level <= 20) {
                    totalAttributes['力量'] = (totalAttributes['力量'] || 0) + supportReinforceValues[level - 1];
                    totalAttributes['智力'] = (totalAttributes['智力'] || 0) + supportReinforceValues[level - 1];
                }
            }
        });
        // 计算附魔加成
        Object.entries(this.data.equipmentEnchant).forEach(([type, enchant]) => {
            if (!enchant) return;
            Object.entries(enchant.attributes).forEach(([attr, value]) => {
                const directions = enchant.attributes['属强加成方向'] ? enchant.attributes['属强加成方向'].split(',') : [];
                if (attr === '属强加成' && !directions.includes(this.data.selectedAttribute) && enchant.attributes['属强加成方向'] !== "全属性") {
                    return;
                }
                if (typeof value !== 'number') return;
                totalAttributes[attr] = (totalAttributes[attr] || 0) + value;
            });
        });
        // 应用职业被动技能加成
        const jobInfo = jobData[this.data.selectedJob];
        if (jobInfo && jobInfo.skillBonus) {
            Object.entries(jobInfo.skillBonus).forEach(([attr, value]) => {
                if (typeof value !== 'number') return;
                totalAttributes[attr] = (totalAttributes[attr] || 0) + value;
            });
        }

        // 计算圣者封印加成
        totalAttributes['黄字'] = (totalAttributes['黄字'] || 0) + 5;
        totalAttributes['物理攻击力'] = 40 + (totalAttributes['物理攻击力'] || 0);
        totalAttributes['魔法攻击力'] = 40 + (totalAttributes['魔法攻击力'] || 0);
        totalAttributes['智力'] = 70 + (totalAttributes['智力'] || 0);
        totalAttributes['力量'] = 70 + (totalAttributes['力量'] || 0);
        // 计算装扮加成
        totalAttributes['力量'] = 70 + (totalAttributes['力量'] || 0);
        totalAttributes['智力'] = 70 + (totalAttributes['智力'] || 0);
        // 宠物装备加成
        totalAttributes['力量'] = 60 + 18 + (totalAttributes['力量'] || 0);
        totalAttributes['智力'] = 60 + 18 + (totalAttributes['智力'] || 0);
        totalAttributes['物理攻击力'] = 60 + 11 + (totalAttributes['物理攻击力'] || 0);
        totalAttributes['魔法攻击力'] = 60 + 11 + (totalAttributes['魔法攻击力'] || 0);
        totalAttributes['属强加成'] = (totalAttributes['属强加成'] || 0) + 14;

        // 根据职业类型选择基础属性和攻击力
        // 设置基础力量/智力为600 其中141为成长加成,114为冒险团加成,65工会加成
        totalAttributes['力量'] = 600 + (totalAttributes['力量'] || 0);
        totalAttributes['智力'] = 600 + (totalAttributes['智力'] || 0);
        totalAttributes['力量百分比'] = (totalAttributes['力量百分比'] || 0);
        totalAttributes['智力百分比'] = (totalAttributes['智力百分比'] || 0);
        // 设置基础物理/魔法攻击力为280
        totalAttributes['物理攻击力'] = 280 + (totalAttributes['物理攻击力'] || 0);
        totalAttributes['魔法攻击力'] = 280 + (totalAttributes['魔法攻击力'] || 0);
        totalAttributes['物攻百分比'] = (totalAttributes['物攻百分比'] || 0);
        totalAttributes['魔攻百分比'] = (totalAttributes['魔攻百分比'] || 0);
        totalAttributes['属强加成'] = totalAttributes['属强加成'] + 15 + 16; // 包括成长和工会
        // 设置固定攻击力为600
        const fixedAttackPower = 600;
        // 人物等级为65级、怪物等级为60
        const characterLevel = 65;
        const monsterLevel = 60;
        // 基础暴击数值 成长系统加了141,工会加了48
        let baseCriticalDamage = 141 + 48;

        // mock 测试是否公式正确
        // mockAttributes(totalAttributes, baseCriticalDamage, baseCriticalRate);

        const physicalBase = totalAttributes['力量'] * (1 + totalAttributes['力量百分比'] / 100) / 250 + 1;
        const magicBase = totalAttributes['智力'] * (1 + totalAttributes['智力百分比'] / 100) / 250 + 1;
        const baseAttribute = isPhysicalJob ? physicalBase : magicBase;

        const physicalAttachPower = totalAttributes['物理攻击力'] * (1 + totalAttributes['物攻百分比'] / 100) + fixedAttackPower;
        const magicAttachPower = totalAttributes['魔法攻击力'] * (1 + totalAttributes['魔攻百分比'] / 100) + fixedAttackPower;
        const attackPower = isPhysicalJob ?
            physicalAttachPower : magicAttachPower;

        const physicalCriticalRate = (totalAttributes['物理暴击率加成'] || 0);
        const magicCriticalRate = (totalAttributes['魔法暴击率加成'] || 0);
        const criticalRate = isPhysicalJob ?
            physicalCriticalRate : magicCriticalRate;

        const criticalDamage = (isPhysicalJob ?
            (totalAttributes['物爆'] || 0) :
            (totalAttributes['魔爆'] || 0)) + baseCriticalDamage;

        const actualCriticalRate = 0.03 + criticalRate / 100 + criticalDamage * 0.0097 / (3.75 * Math.pow(1.25, (monsterLevel / 8)));

        // 计算其他加成
        const yellowMod = (totalAttributes['黄字'] || 0) / 100;
        const whiteMod = (totalAttributes['白字'] || 0) / 100;
        const criticalMod = (totalAttributes['爆伤'] || 0) / 100;
        const skillDamageMod = (totalAttributes['技能攻击力加成'] || 0) / 100;

        // 根据属强加成方向计算属强加成 TODO
        const elementalCount = (totalAttributes['属强加成'] || 0);
        const elementalDamageMod = (totalAttributes['属性伤害百分比'] || 0) / 100;

        const elementalFactor = (1.05 + elementalCount * 0.0045);
        const elementalWhiteFactor = (1 + 1.015 * (whiteMod + elementalDamageMod * elementalFactor))

        // 防御系数
        const chongziDefense = 22955;

        const defenseMod = 1 - chongziDefense / (chongziDefense + characterLevel * 200);
        // 计算基础倍率
        const damage = baseAttribute * attackPower *
            (1 + yellowMod) * elementalFactor *
            elementalWhiteFactor *
            (1 + (0.5 + criticalMod) * actualCriticalRate) *
            (1 + skillDamageMod) *
            defenseMod;
        // console.log('攻击力系数', attackPower,
        //      '力智系数',baseAttribute,
        //      '属强系数', elementalFactor,
        //      '属强白字系数', elementalWhiteFactor,
        //      '实际暴击率', actualCriticalRate,
        //      '黄字系数', yellowMod,
        //      '白字系数', whiteMod,
        //      '爆伤系数', criticalMod,
        //      '技攻系数', skillDamageMod,
        //      '防御系数', defenseMod)
        // console.log('基础倍率', damage)

        // 创建当前装备配置的记录
        const currentTime = new Date();
        const currentRecord = {
            timestamp: `${currentTime.getHours()}:${currentTime.getMinutes()}:${currentTime.getSeconds()}`,
            damage: Math.floor(damage).toString(),
            job: this.data.selectedJob,
            attribute: this.data.selectedAttribute,
            equipment: {...this.data.selectedEquipmentLabelMap },
            showDetail: false, // 添加折叠状态标记
            badges: {...this.data.equipmentBadges },
            reinforce: {...this.data.equipmentReinforce },
            enchant: {...this.data.equipmentEnchant },
        };

        totalAttributes['面板力量'] = Math.round(totalAttributes['力量'] * (1 + totalAttributes['力量百分比'] / 100), 2);
        totalAttributes['面板智力'] = Math.round(totalAttributes['智力'] * (1 + totalAttributes['智力百分比'] / 100), 2);
        totalAttributes['面板物理攻击力'] = Math.round(physicalAttachPower * (totalAttributes['力量'] / 250 + 1), 2);
        totalAttributes['面板魔法攻击力'] = Math.round(magicAttachPower * (totalAttributes['智力'] / 250 + 1), 2);
        totalAttributes['面板物理暴击率'] = physicalCriticalRate;
        totalAttributes['面板魔法暴击率'] = magicCriticalRate;
        totalAttributes['面板物爆'] = (totalAttributes['物爆'] || 0) + baseCriticalDamage;
        totalAttributes['面板魔爆'] = (totalAttributes['魔爆'] || 0) + baseCriticalDamage;
        this.setData({
            damageResult: Math.floor(damage).toString(),
            damageHistory: [currentRecord, ...this.data.damageHistory].slice(0, 5),
            needRecalculate: false,
            nowTotalAttributes: totalAttributes
        });
        this.saveOpt();
    },
    // 切换装备明细的显示状态
    toggleEquipmentDetail(e) {
        const index = e.currentTarget.dataset.index;
        this.setData({
            [`damageHistory[${index}].showDetail`]: !this.data.damageHistory[index].showDetail
        });
    },

    onEquipmentChange(e) {
        const { type } = e.currentTarget.dataset;
        const index = e.detail.value;
        const labelValue = this.data.thisEquipmentLabelMap[type][index];
        const equipment = equipmentMap[type][index];
        this.setData({
            [`selectedEquipmentLabelMap.${type}`]: labelValue,
            [`selectedEquipmentMap.${type}`]: equipment,
            needRecalculate: true
        }, () => {
            // 检查套装效果
            this.getSetEffects();
        });
        // 如果是戒指部位，需要重新初始化徽章数据
        if (type === '戒指') {
            this.setData({
                [`equipmentBadges.${type}`]: this.getBadgeInitialValue(type, labelValue),
            });
        }
        // console.log(this.data.selectedEquipmentMap)
        // console.log(this.data.selectedEquipmentLabelMap)
    },
    onJobChange(e) {
        const { type } = e.currentTarget.dataset;
        const index = e.detail.value;
        const job = this.data.jobs[index];
        this.setData({
            selectedJob: job,
            needRecalculate: true
        }, () => {
            this.autoSelectEquipment();
        }, () => {
            // 检查套装效果
            this.getSetEffects();
        });
    },
    // 处理属性选择
    onAttributeChange(e) {
        const attribute = this.data.attributes[e.detail.value];
        this.setData({ selectedAttribute: attribute, needRecalculate: true });
    },
    autoSelectEquipment() {
        if (this.data.selectedJob === undefined) {
            return;
        }
        const selectedEquipmentMap = {};
        const equipmentMultiIndex = {};

        this.data.thisEquipmentTypes.forEach(type => {
            const equipments = equipmentMap[type] || [];
            // console.log(equipments)
            if (equipments.length > 0) {
                let selectEquipment = null;
                // 如果是防具，优先选择本命防具，否则随机
                if (this.data.armorTypes.find(item => item === type)) {
                    selectEquipment = equipments.filter(item => item.装备类型 === jobData[this.data.selectedJob]['armorMaster'])[2];
                }
                if (type === "武器") {
                    const preferredWeaponType = jobData[this.data.selectedJob]['weaponMaster'][0];
                    const weaponEquipments = equipments.filter(item => item.装备类型 === preferredWeaponType);
                    selectEquipment = weaponEquipments[1];
                }
                if (!selectEquipment) {
                    const index = Math.floor(Math.random() * equipments.length);
                    selectEquipment = equipments[index];
                    selectEquipment = equipments[equipments.length - 1];
                }
                this.setData({
                    [`selectedEquipmentLabelMap.${type}`]: `${selectEquipment.装备名称}(${selectEquipment.装备类型})(${selectEquipment.装备等级}级)`,
                    // 根据部位设置徽章
                    [`equipmentBadges.${type}`]: this.getBadgeInitialValue(type, selectEquipment.装备名称),
                    [`equipmentEnchant.${type}`]: this.data.enchantableTypes.includes(type) ? this.data.enchantOptions[type][this.data.enchantOptions[type].length - 1] : null
                });
                const typeIndex = this.data.equipmentMultiArray[type] ? this.data.equipmentMultiArray[type][0].indexOf(selectEquipment.装备类型) : -1;
                if (typeIndex !== -1) {
                    // 更新第一列索引
                    equipmentMultiIndex[type] = [typeIndex, 0];
                    // 获取该类型下的所有装备名称
                    const typeEquipments = equipments.filter(item => item.装备类型 === selectEquipment.装备类型)
                        .map(item => `${item.装备名称}(${item.装备等级}级)`);
                    // 更新第二列索引
                    this.setData({
                        [`equipmentMultiArray.${type}[1]`]: typeEquipments
                    });
                    // 找到当前装备在第二列中的索引
                    const equipmentIndex = typeEquipments.indexOf(`${selectEquipment.装备名称}(${selectEquipment.装备等级}级)`);
                    if (equipmentIndex !== -1) {
                        // 更新第二列索引
                        equipmentMultiIndex[type] = [typeIndex, equipmentIndex];
                    }
                }

                selectedEquipmentMap[type] = selectEquipment;
            }
        });

        this.setData({
            hasSelectedEquipment: true,
            selectedEquipmentMap: selectedEquipmentMap,
            equipmentMultiIndex: equipmentMultiIndex,
            needRecalculate: true
        });
    },
    mockAttributes(attributes, baseCriticalDamage, baseCriticalRate) {
        totalAttributes['力量'] = 1478;
        totalAttributes['智力'] = 1478;
        totalAttributes['力量百分比'] = 0;
        totalAttributes['智力百分比'] = 0;
        totalAttributes['物理攻击力'] = 763;
        totalAttributes['魔法攻击力'] = 763;
        totalAttributes['物攻百分比'] = 0;
        totalAttributes['魔攻百分比'] = 0;
        totalAttributes['黄字'] = 0;
        totalAttributes['白字'] = 8;
        totalAttributes['爆伤'] = 0;
        totalAttributes['属强加成方向'] = '全属性';
        totalAttributes['属强加成'] = 0;
        totalAttributes['属性伤害百分比'] = 0;
        totalAttributes['技能攻击力加成'] = 30;
        baseCriticalDamage = 650;
        baseCriticalRate = 22;
    }
});